package com.ch.ms.server.login.service.impl;

import com.ch.ms.data.domain.character.ChmsCharacter;
import com.ch.ms.service.character.ChmsCharacterCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Service;

import java.util.Objects;


@Service
public class ChmsCharacterCacheServiceImpl implements ChmsCharacterCacheService {


    private SetOperations<String, ChmsCharacter> characterSetOperations;

    @Autowired
    public ChmsCharacterCacheServiceImpl(RedisTemplate<String, ChmsCharacter> chmsCharacterRedisTemplate) {
        this.characterSetOperations = chmsCharacterRedisTemplate.opsForSet();
    }


    @Override
    public ChmsCharacter save(ChmsCharacter entity) {
        characterSetOperations.add(getKey(entity), entity);
        return entity;
    }

    @Override
    public void saveAll(Iterable<ChmsCharacter> entities) {

        if (Objects.isNull(entities)) return;
        entities.forEach(this::save);

    }

    @Override
    public String getKey(Object... args) {
        if (args[0] instanceof ChmsCharacter)
            return String.format("%s:characters", ((ChmsCharacter) args[0]).getAccount().getUserName());


        return null;
    }
}
